﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using UnityEngine.Events;

public class CameraShake : MonoBehaviour
{
    // Start is called before the first frame update
    public float ShakeDuration = 0.3f;
    public float ShakeAmplitude = 1.2f;
    public float ShakeFrequency = 2.0f;
    public float ShakeElapedTime = 0f;
    public bool NeedShake = false;

    static CameraShake current;
    public CinemachineVirtualCamera virtualCamera;
    private CinemachineBasicMultiChannelPerlin virtualCameraNoise;
    void Start()
    {
        if (virtualCamera != null)
        {
            virtualCameraNoise = virtualCamera.GetCinemachineComponent<Cinemachine.CinemachineBasicMultiChannelPerlin>();
        }
        if (current != null)
        {
            Destroy(gameObject);
            return;
        }
        current = this;
        DontDestroyOnLoad(gameObject);
    }

    // Update is called once per frame
    void Update()
    {

    }
    private void FixedUpdate()
    {

    }
    public static void SetDuration()
    {
        current.NeedShake = true;
        current.Invoke("Stop", 1f);
    }
    public static void CameraShakeManager()

    { 
        if(current.NeedShake)
        {
        current.ShakeElapedTime = current.ShakeDuration;
        }
        else 
        {
            current.ShakeElapedTime = 0;
        }
    
        if (current.virtualCamera != null || current.virtualCameraNoise != null)
        {
            if (current.ShakeElapedTime > 0)
            {
                current.virtualCameraNoise.m_AmplitudeGain = current.ShakeAmplitude;
                current.virtualCameraNoise.m_FrequencyGain = current.ShakeFrequency;
                current.ShakeElapedTime = Time.deltaTime;
            }
            else
            {
                current.virtualCameraNoise.m_AmplitudeGain = 0f;
                current.ShakeElapedTime = 0f;
}
        }
    }
    void Stop()
    {
        Debug.Log("stop");
        current.NeedShake = false;
    }

}
